<template>
  <div>
    <a-card :bordered="false" :bodyStyle="tstyle">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="5" :sm="24">
              <a-form-item label="学院">
                <!-- 如果只有一条disabled -->
                <a-select
                  :disabled="this.collList.length === 1"
                  show-search
                  allowClear
                  placeholder="请选择所属学院"
                  v-model="queryParam.collegeId"
                  @change="changeCollege">
                  <a-select-option v-for="item of this.collList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="开课课程">
                <a-select
                  show-search
                  allowClear
                  placeholder="请选择开课课程"
                  v-model="queryParam.courseId"
                  :disabled="!queryParam.collegeId">
                  <a-select-option v-for="item of this.courseList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="开课学年">
                <a-select show-search allowClear placeholder="请选择开课学年" @change="changeSchoolYear" v-model="queryParam.schoolYearId">
                  <a-select-option v-for="item of this.schoolYearList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="开课学期">
                <a-select show-search allowClear placeholder="请选择开课学期" v-model="queryParam.termId">
                  <a-select-option v-for="item of this.schoolTermList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  @click="resetQueryParam"
                >重置</a-button
                >
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false">
      <s-table ref="table" :columns="columns" :data="loadData" :rowKey="(record) => record.id">
        <template class="table-operator" slot="operator">
          <a-button type="primary" icon="plus" @click="$refs.detail.open(undefined, false)">新增开课课程</a-button>
        </template>
        <span slot="courseChooseTime" slot-scope="text, record">{{ record.selectionStartDate }} - {{ record.selectionEndDate }}</span>
        <span slot="publishState" slot-scope="text, record">
          <a-tag color="red" v-if="record.publishState === 0">待发布</a-tag>
          <a-tag color="green" v-if="record.publishState === 1">已发布</a-tag>
        </span>
        <span slot="action" slot-scope="text, record">
          <!-- 开课状态为：未发布，或者选课状态不是已确认 -->
          <a @click="$refs.detail.open(record)" v-if="record.publishState === 0 || record.confirmState !== 4">编辑</a>

          <a-divider type="vertical" v-if="record.publishState === 0 || record.confirmState !== 4"/>

          <a @click="$refs.detail.open(record, true)">查询</a>

          <template
            v-if="record.publishState === 0 && record.frequencyCount > 0 && record.selectionStartDate && record.selectionEndDate">
            <a-divider type="vertical"/>

            <a-popconfirm
              title="确认发布？【开课课程一旦发布，除“选课时间”和”开放学生“外其他信息不可编辑。】"
              @confirm="() => publishCoursePublish(record.id)">
              <a>发布</a>
            </a-popconfirm>
          </template>

          <template v-if="record.publishState === 1">
            <a-divider type="vertical"/>
            <a-popconfirm title="确认撤回？" @confirm="() => rollbackCoursePublish(record.id)">
              <a>撤回</a>
            </a-popconfirm>
          </template>

          <a-divider type="vertical"/>
          <a @click="goCourseSchedule(record)">实验项目</a>
          <a-divider type="vertical"/>
          <a @click="goCourseSelectionMgmt(record)">选课管理</a>
          <a-divider type="vertical"/>
          <a-popconfirm placement="topRight" title="您是否确认需要复制当前的开课课程？" @confirm="() => copyData(record.id)">
            <a>复制课程</a>
          </a-popconfirm>
          <a-divider type="vertical" v-if="record.publishState === 0"/>
          <a-popconfirm
            placement="topRight"
            title="确认删除？"
            @confirm="() => singleDelete(record)"
            v-if="record.publishState === 0">
            <a>删除</a>
          </a-popconfirm>
        </span>
      </s-table>
    </a-card>
    <sys-college-detail ref="detail" @ok="handleOk"/>
  </div>
</template>
<script>
  import { STable, XDown } from '@/components'
  import {
    coursePublishPageWithName,
    coursePublishPublish,
    coursePublishRollback,
    coursePublishDelete,
    coursePublishCopy
  } from '@/api/modular/main/coursePublishManage'
  import { sysCollegeList } from '@/api/modular/system/sysCollegeManage'
  import { sysSchoolYearList } from '@/api/modular/system/sysSchoolYearManage'
  import { sysSchoolTermList } from '@/api/modular/system/sysSchoolTermManage'
  import { courseList } from '@/api/modular/system/courseManage'

  import SysCollegeDetail from './detail'

  export default {
    components: {
      STable,
      XDown,
      SysCollegeDetail
    },
    data() {
      return {
        courseList: [],
        collList: [],
        schoolYearList: [],
        schoolTermList: [],
        // 查询参数
        queryParam: {
          collegeId: undefined,
          courseId: undefined,
          termId: undefined,
          schoolYearId: undefined
        },
        // 表头
        columns: [
          {
            title: '学院',
            align: 'center',
            dataIndex: 'collegeName'
          },
          {
            title: '开课课程ID',
            align: 'center',
            dataIndex: 'id'
          },
          {
            title: '开课课程',
            align: 'center',
            dataIndex: 'courseName'
          },
          {
            title: '开课学年',
            align: 'center',
            dataIndex: 'schoolYearName'
          },
          {
            title: '开课学期',
            align: 'center',
            dataIndex: 'termName'
          },
          {
            title: '开课轮次',
            align: 'center',
            dataIndex: 'frequencyCount'
          },
          {
            title: '开课状态',
            align: 'center',
            dataIndex: 'publishState',
            scopedSlots: { customRender: 'publishState' }
          },
          {
            title: '选课时间',
            align: 'center',
            dataIndex: 'courseChooseTime',
            scopedSlots: { customRender: 'courseChooseTime' }
          },
          {
            title: '选课状态',
            align: 'center',
            dataIndex: 'selectionState'
          },
          {
            title: '操作',
            width: '220px',
            align: 'center',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' }
          }
        ],
        tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
        // 加载数据方法 必须为 Promise 对象
        loadData: (parameter) => {
          return coursePublishPageWithName(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        }
      }
    },
    created() {
      this.getCollList()
      this.getSchoolYearList()
      this.getSchoolTermList()
    },
    methods: {
      resetQueryParam() {
        if (this.collList.length === 1) {
          this.queryParam = {
            ...this.queryParam,
            courseId: undefined,
            termId: undefined,
            schoolYearId: undefined
          }
        } else {
          this.queryParam = {
            collegeId: undefined,
            courseId: undefined,
            termId: undefined,
            schoolYearId: undefined
          }
        }
      },
      /**
       * load学院列表
       */
      getCollList() {
        sysCollegeList().then((res) => {
          if (res.success) {
            this.collList = res.data
            if (this.collList.length === 1) {
              // 如果只有一条，默认选上
              this.queryParam.collegeId = this.collList[0].id
              this.getCourseList()
            }
          }
        })
      },
      /**
       * load学年列表
       */
      getSchoolYearList() {
        sysSchoolYearList().then((res) => {
          if (res.success) {
            this.schoolYearList = res.data
          }
        })
      },
      /**
       * load开课学期
       */
      getSchoolTermList(schoolYearId) {
        sysSchoolTermList({
          schoolYearId: schoolYearId
        }).then((res) => {
          if (res.success) {
            this.schoolTermList = res.data
          }
        })
      },
      /**
       * load课程
       */
      getCourseList() {
        courseList({
          collId: this.queryParam.collegeId
        }).then((res) => {
          if (res.success) {
            this.courseList = res.data
          }
        })
      },
      changeCollege() {
        this.queryParam.courseId = undefined
        this.getCourseList()
      },
      /**
       * 单个删除
       */
      singleDelete(record) {
        const param = [{ id: record.id }]
        coursePublishDelete(param).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.clearRefreshSelected()
          } else {
            this.$message.error('删除失败') // + res.message
          }
        })
      },
      /**
       * 发布
       */
      publishCoursePublish(coursePublishId) {
        coursePublishPublish(coursePublishId).then((res) => {
          if (res.success) {
            this.$message.success('发布成功')
          } else {
            this.$message.error('发布失败：' + res.message)
          }
          setTimeout(() => {
            this.$refs.table.refresh()
          }, 400)
        })
      },
      /**
       * 撤回
       */
      rollbackCoursePublish(coursePublishId) {
        coursePublishRollback(coursePublishId).then((res) => {
          if (res.success) {
            this.$message.success('撤回成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('撤回失败：' + res.message)
          }
        })
      },
      handleOk() {
        this.$refs.table.refresh()
      },
      copyData(id) {
        coursePublishCopy(id).then((res) => {
          if (res.success) {
            this.$message.success('复制成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('复制失败：' + res.message)
          }
        })
      },
      goCourseSchedule(record) {
        this.$router.push({ name: 'CourseSchedule', params: record })
      },
      goCourseSelectionMgmt(record) {
        this.$router.push({ name: 'course_selection_mgmt', params: record })
      },
      changeSchoolYear(schoolYearId) {
        this.queryParam.termId = undefined
        this.getSchoolTermList(schoolYearId)
      }
    }
  }
</script>
<style lang="less">
  .table-operator {
    margin-bottom: 18px;
  }

  button {
    margin-right: 8px;
  }
</style>
